
import 'package:flutter/material.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/models/entity/osc_tweet.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/pages/comment/tweet_comment_list.dart';
import 'package:osc/ui/pages/like/tweet_like_list.dart';
import 'package:osc/ui/pages/tweet/publish_tweet.dart';
import 'package:osc/ui/pages/tweet/tweet_content.dart';
import 'package:osc/ui/widgets/comment/tweet_comment_bar_widget.dart';
import 'package:osc/ui/widgets/comment/tweet_comment_input_widget.dart';
import 'package:osc/ui/widgets/common_scaffold.dart';
import 'package:osc/ui/widgets/common_tab_bar.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';

///动弹
class TweetDetail extends StatefulWidget {
  final OscTweet tweet;
  final bool needLogin;
  final bool enableLoadMore;
  final double expandedHeight;


  const TweetDetail({Key key, this.tweet, this.needLogin = false, this.enableLoadMore = true, this.expandedHeight}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new TweetDetailState(tweet, needLogin, enableLoadMore, expandedHeight);
  }
}

class TweetDetailState extends State<TweetDetail>  with SingleTickerProviderStateMixin<TweetDetail>{
  final OscTweet tweet;
  final bool needLogin;
  final bool enableLoadMore;
  final double expandedHeight;
  TweetDetailState(this.tweet, this.needLogin, this.enableLoadMore, this.expandedHeight);


  double paddingParentHorizontal = Dimens.gap_activity_horizontal;
  double paddingChildHorizontal = Dimens.gap_view_normal;
  double paddingChildVertical = Dimens.gap_view_normal;

  double portraitSize = Dimens.view_item_icon_height_biggest;

  FocusNode focusNode = FocusNode();
  bool showKeyBord = false;

  String commentContent = "";


  HttpRepository httpRepository;


  @override
  void initState() {
    super.initState();
    httpRepository = HttpRepository();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    double bottomHeight = MediaQuery.of(context).viewInsets.bottom;
    if (bottomHeight > 50) {
      showKeyBord = true;
    } else {
      showKeyBord = false;
      FocusScope.of(context).requestFocus(FocusNode());
    }
    setState(() {

    });
  }

  @override
  void dispose() {
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return CommonScaffold(
      title: "猿圈详情",
      body: Stack(
        children: <Widget>[
          NestedScrollView(
            headerSliverBuilder: (context, bool innerBoxIsScrolled){
              return [
                buildSliverAppBar(context),
              ];
            },
            body: Column(
              children: <Widget>[
                Expanded(
                  child: buildList(),
                ),
                TweetCommentBarWidget(
                  id: tweet.id,
                  comment: commentContent,
                  liked: tweet.liked,
                  callback: ({showInputWidget, rePost, reverseLike}){
                    if(showInputWidget){
                      setState(() {
                        showKeyBord = true;
                        FocusScope.of(context).requestFocus(focusNode);
                      });
                    } else if(rePost){
                      String originContent = tweet.content;
                      if(tweet.about != null && !StringUtil.isEmpty(tweet.about.content)){
                        originContent = StringUtil.clearHtmlContent(tweet.about.content);
                      }
                      jumpToPageForResult(PublishTweet(
                        originAuthorName: tweet.author.name,
                        originContent: originContent,
                        tweetContent: StringUtil.clearHtmlContent(tweet.content),
                        aboutFromTweetId: tweet.id,
                        aboutId: tweet.about?.id??tweet.id,
                      ));
                    } else if(reverseLike){
                      reverseTweetLike(tweet.id);
                    }
                  },
                )
              ],
            ),
          ),
          Positioned(
            bottom: 0,
            child: Offstage(
              offstage: !showKeyBord,
              child: TweetCommentInputWidget(content: commentContent, focusNode: focusNode, commentInputContentCallback: ({bool submit, String content}){
                if(submit){
                  publishComment(tweet.id, content);
                  commentContent = "";
                  showKeyBord = false;
                  FocusScope.of(context).requestFocus(FocusNode());
                  setState(() {

                  });
                } else {
                  commentContent = content;
                }
              },),
            ),
          ),
        ],
      ),
    );
  }

  buildSliverAppBar(BuildContext context){
    return SliverAppBar(
      leading: null,
      primary: true,//是否预留高度,ture时在状态栏下，false 最上面
      forceElevated: false,//是否显示阴影
      automaticallyImplyLeading: false,
      titleSpacing: NavigationToolbar.kMiddleSpacing,
      snap: false,//折叠效果，与floating结合使用，如果为true则floating必须为true,就是往下滑一点整个大背景就显示全部，往上滑动整个导航内容就隐藏
      floating: false,//是否随滑动隐藏标题,则滑动到最上面再滑动是否隐藏标题，ture隐藏
      expandedHeight: expandedHeight+Dimens.gap_divider_height_smallest,//展开高度，默认是状态栏加标题的高度
      pinned: false,//是否固定导航在顶部，true 固定，false不固定，再上滑导航隐藏
      flexibleSpace: FlexibleSpaceBar(//展开区域
        centerTitle: false,
        title: Text(""),
        collapseMode: CollapseMode.pin,//背景 固定到位，直到达最小范围，默认 parallax（将以视差方式滚动）
        background: Container(
          color: Colors.red,
          child: buildTweetContent(),
        ),
      ),
    );
  }

  buildTweetContent(){
    return Container(
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          TweetContent(tweet: tweet,),
          SmallWidgets.buildLine(),
        ],
      ),
    );
  }

  buildList(){
    return CommonTabBar(
        tabs: [
          Tab(text:"评论(${tweet.commentCount})"),
          Tab(text:"赞(${tweet.likeCount})"),
        ],
        pages: [
          TweetCommentList(id: tweet.id),
          TweetLikeList(id: tweet.id),
        ],
    );
  }

  buildComment(){

  }

  buildText(String data, Color color, double fontSize) {
    return SmallWidgets.buildText(data, color, fontSize);
  }

  jump2PageForResult(Widget page, {bool checkLogin = false}) {
    if(checkLogin){
      if(OscUserManager.getInstance().isLogin()){
        jumpToPageForResult(page);
      } else {
        jumpToPageForResult(LoginPage());
        showTips(StringIds.userNoLogin);
      }
    } else {
      jumpToPageForResult(page);
    }
  }
  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }


  publishComment(int id, String content) async{
    if(StringUtil.isEmpty(content)){
      showTips("请输入评论内容");
      FocusScope.of(context).requestFocus(focusNode);
      return;
    }
    await httpRepository.commentTweet(sourceId: id, content: content).then((resp) {
      showTips(resp.success? "评论成功" : "评论失败");
    });
  }

  reverseTweetLike(int id) async{
    await httpRepository.reverseTweetLike(sourceId: id).then((resp){
      if(resp.success){
        tweet.liked = resp.result.liked;
        tweet.likeCount = resp.result.likeCount;
        if(mounted){
          setState(() {

          });
        }
      } else {
        showTips(resp.message);
      }
    });
  }
}
